﻿using System.Collections.Generic;
using RN.ERP.Web.ModelService;
using Newtonsoft.Json;
using Fly.Common.Linq;
using RN.ERP.Web.PersonService;
using System.Linq;
using System.Web.UI.WebControls;
using System;
using System.Web.UI;
using Telerik.Web.UI;

namespace RN.ERP.Web.Expert
{
    /// <summary>
    /// 专家系统主管端首页
    /// </summary>
    public partial class ExpertManagerMain : BasePage
    {
        #region 属性、变量

        protected string AreaCode
        {
            get
            {
                return UserInfo.LocalArea;
            }
        }
        protected string CorpUserGuid
        {
            get
            {
                return UserInfo.CorpUserGuid;
            }
        }
        protected string RoleId
        {
            get
            {
                return UserInfo.RoleId;
            }
        }

        /// <summary>
        /// 是否是有条件通过
        /// </summary>
        protected string IsLimitedPass
        {
            get
            {
                return hidIsLimitedPass.Value;
            }
        }
#if DEBUG
        public override bool IsCheckPermission
        {
            get { return false; }
        }
#endif
       
        private EnterpriseService.EnterpriseServiceClient enterpriseServiceClient = new EnterpriseService.EnterpriseServiceClient();
        private BasicService.BasicServiceClient basicServiceClient = new BasicService.BasicServiceClient();
        private PersonServiceClient personClient = new PersonServiceClient();
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindFlowCode();
            }
        }

        /// <summary>
        /// 客户端grid刷新
        /// </summary>
        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            switch (e.Argument)
            {
                case "Person":
                    rgPersonList.MasterTableView.SortExpressions.Clear();
                    rgPersonList.MasterTableView.GroupByExpressions.Clear();
                    rgPersonList.Rebind();
                    break;
                #region Audit
                case "Audit":
                    try
                    {
                        int checkCount = 0;
                        string flowcode = string.Empty;
                        string strGuid = string.Empty;
                        string comments = hdnComments.Value;
                        List<string> list = new List<string>();
                        foreach (GridDataItem dataItem in rgPersonList.MasterTableView.Items)
                        {
                            if ((dataItem.FindControl("CheckBox1") as CheckBox).Checked == true)
                            {
                                strGuid = dataItem.GetDataKeyValue("EmpGuid").ToString();
                                flowcode = dataItem["FlowCode"].Text;
                                checkCount++;
                                list.Add(strGuid);
                            }
                        }
                        if (checkCount == 0)
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('请选择要审核的数据！');", true);
                        }
                        else if (checkCount >= 1)
                        {
                            string ret = AuditExpert(list, "5", flowcode, "评标专家审核");
                            OperationResult result = JsonConvert.DeserializeObject<OperationResult>(ret);
                            if (result.Result == true)
                            {
                                rgPersonList.Rebind();
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                            }
                            else
                            {
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        hidSysError.Value = ex.Message;
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('数据加载失败！');", true);
                    }
                    break;
                #endregion
                #region Back
                case "Back":
                    try
                    {
                        int checkCount = 0;
                        string flowcode = string.Empty;
                        string strGuid = string.Empty;
                        List<string> list = new List<string>();
                        foreach (GridDataItem dataItem in rgPersonList.MasterTableView.Items)
                        {
                            if ((dataItem.FindControl("CheckBox1") as CheckBox).Checked == true)
                            {
                                strGuid = dataItem.GetDataKeyValue("EmpGuid").ToString();
                                flowcode = dataItem["FlowCode"].Text;
                                checkCount++;
                                list.Add(strGuid);
                            }
                        }
                        if (checkCount == 0)
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('请选择要退回的数据！');", true);
                        }
                        else if (checkCount >= 1)
                        {
                            string ret = AuditExpert(list, "6", flowcode, "评标专家退回");
                            OperationResult result = JsonConvert.DeserializeObject<OperationResult>(ret);
                            if (result.Result == true)
                            {
                                rgPersonList.Rebind();
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                            }
                            else
                            {
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        hidSysError.Value = ex.Message;
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('数据加载失败！');", true);
                    }
                    break;
                #endregion
                default:
                    break;
            }
        }

        private string AuditExpert(List<string> data, string opt, string flowcode, string content)
        {
            string currentAreaCode = UserInfo.CurrentArea;
            User_Log log = new User_Log();
            log.IsrtUserArea = IsLimitedPass;
            log.FunctionId = opt;
            log.FunctionType = content;
            log.Notice = hdnComments.Value;

            var result = personClient.ExpertInfoPost(UserInfo.CorpUserGuid, JsonConvert.SerializeObject(data), JsonConvert.SerializeObject(log), currentAreaCode);
            return result;
        }

        private void BindFlowCode()
        {
            string msg = string.Empty;
            var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(basicServiceClient.GetAllBusinessStatusAndProcessing(out msg, UserInfo.RoleId, "00", "8065", false));
            string flowCode = string.Empty;
            if (dic != null)
            {
                var flow = dic.Where(o => o.Value.Contains("处理中")).FirstOrDefault();
                if (flow.Key != null)
                {
                    flowCode = flow.Key;
                }
            }
            ddlStatus.Items.Clear();
            ddlStatus.Items.Add(new ListItem("待处理", flowCode));
            ddlStatus.Items.Insert(0, new ListItem("全部", "99"));
            if (dic.ContainsValue("处理中"))
            {
                ddlStatus.Items.FindByText("待处理").Selected = true;
            }
        }

        protected void ToggleRowSelection(object sender, EventArgs e)
        {
            ((sender as CheckBox).NamingContainer as GridItem).Selected = (sender as CheckBox).Checked;
            bool checkHeader = true;
            foreach (GridDataItem dataItem in rgPersonList.MasterTableView.Items)
            {
                if (!(dataItem.FindControl("CheckBox1") as CheckBox).Checked)
                {
                    checkHeader = false;
                    break;
                }
            }
            GridHeaderItem headerItem = rgPersonList.MasterTableView.GetItems(GridItemType.Header)[0] as GridHeaderItem;
            (headerItem.FindControl("headerChkbox") as CheckBox).Checked = checkHeader;
        }

        protected void ToggleSelectedState(object sender, EventArgs e)
        {
            CheckBox headerCheckBox = (sender as CheckBox);
            foreach (GridDataItem dataItem in rgPersonList.MasterTableView.Items)
            {
                (dataItem.FindControl("CheckBox1") as CheckBox).Checked = headerCheckBox.Checked;
                dataItem.Selected = headerCheckBox.Checked;
            }
        }

        #region 人员审核
        
        /// <summary>
        /// 拼接查询条件
        /// </summary>
        /// <returns></returns>
        private string GetQueryConditions()
        {
            List<string> listFlow = GetFlowCodes();
            List<QueryPersonInfoCondition> queryList = new List<QueryPersonInfoCondition>();
            string areaCode = AreaCode;
            
            QueryPersonInfoCondition cond;
            foreach (var f in listFlow)
            {
                cond = new QueryPersonInfoCondition();
                if (f != "99")
                {
                    cond.FlowCode = new ParameterValue<string>() { O = OptEnum.Equal, V = f };
                }
                string title = txtName.Text.Trim();
                if (!string.IsNullOrEmpty(title))
                {
                    cond.Name = new ParameterValue<string>() { O = OptEnum.Like, V = title };
                }
                if (AreaCode != "00")
                {
                    cond.AreaCode = new ParameterValue<string>() { O = OptEnum.StartWith, V = areaCode };
                    if (AreaCode != "01"&&UserInfo.RoleId != null && UserInfo.RoleId == "87")
                    {
                        if (f == "0,019" || f == "0,019,022")
                       {
                           string area=areaCode.Substring(0,2)+"01";
                           cond.AreaCode = new ParameterValue<string>() { O = OptEnum.Equal, V = area };
                       }
                    }
                }
                queryList.Add(cond);
            }
            return JsonConvert.SerializeObject(queryList);
        }

        private List<string> GetFlowCodes()
        {
            string msg = string.Empty;
            var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(basicServiceClient.GetAllBusinessStatusAndProcessing(out msg, UserInfo.RoleId, "00", "8065", false));
            string flowCode = string.Empty;
            List<string> listFlow = new List<string>();
            if (ddlStatus.SelectedValue == "99")
            {
                listFlow.Add("99");
            }
            else
            {
                if (dic != null)
                {
                    var flow = dic.Where(o => o.Value.Contains("处理中")).FirstOrDefault();
                    if (flow.Key != null)
                    {
                        flowCode = flow.Key;
                    }
                }
                foreach (var f in flowCode.Split('@'))
                {
                    if (!string.IsNullOrEmpty(f))
                    {
                        if (!(UserInfo.RoleId == "96" && f.StartsWith("1,")))
                        {
                            listFlow.Add(f);
                        }
                    }
                }
            }
            return listFlow;
        }
        
        /// <summary>
        /// 绑定专家信息
        /// </summary>
        public void rgPersonList_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            var queryCondition = GetQueryConditions();
            int pageSize = rgPersonList.MasterTableView.PageSize;
            int pageIndex = rgPersonList.CurrentPageIndex + 1;
            int count = 0;
            var experts = personClient.GetExpertsList(pageIndex, pageSize, queryCondition, UserInfo.CurrentArea, out count);
            var listExperts = JsonConvert.DeserializeObject<IList<tb_Emp_Manager>>(experts).ToList();
            int cnt = count;
            rgPersonList.VirtualItemCount = cnt;
            rgPersonList.DataSource = listExperts;
        }

        #endregion

    }
}
